package com.cn.qgx428.orderingmeal.adapter;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.cn.qgx428.orderingmeal.R;
import com.cn.qgx428.orderingmeal.Store;
import com.cn.qgx428.orderingmeal.animation.FoodToCar;
import com.cn.qgx428.orderingmeal.dialog.FoodSMInfo;
import com.cn.qgx428.orderingmeal.myClass.Car;
import com.cn.qgx428.orderingmeal.myClass.Food;
import com.cn.qgx428.orderingmeal.myClass.MyKeyInfo;
import com.cn.qgx428.orderingmeal.myClass.Shop;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.datatype.BmobPointer;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;

/**
 * Created by QinX on 2017/4/8.
 */

public class SearchFoodAdatper extends RecyclerView.Adapter<SearchFoodAdatper.SearchFoodViewHolder> {

    private static final String TAG = "SearchFoodAdapter";

    private MyKeyInfo keyInfo;

    private Activity activity;
    private Context context;
    private List<Food> foods;

    private static final int GET_START_LOCATION = 0;
    private static final int GET_END_LOCATION = 1;

    public SearchFoodAdatper(Activity activity,Context context, List<Food> foods, MyKeyInfo keyInfo){
        this.activity = activity;
        this.context = context;
        this.foods = foods;
        this.keyInfo = keyInfo;
    }

    @Override
    public SearchFoodViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View viewItem = LayoutInflater.from(context).inflate(R.layout.search_food_item, parent , false);
        SearchFoodViewHolder viewHolder = new SearchFoodViewHolder(viewItem);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(SearchFoodViewHolder holder, final int position) {
        final Food food = foods.get(position);
        holder.foodName.setText(food.getName());
        holder.foodPrice.setText(food.getPrice().toString());
        Picasso.with(context).load(food.getPic().getFileUrl()).fit().into(holder.foodImage);
        holder.LBtnToShop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Shop shop = food.getShop();
                keyInfo.setNowShopName(shop.getName());
                keyInfo.setNowShopID(shop.getObjectId());
                keyInfo.setNowPicUrl(shop.getImg().getFileUrl());
                keyInfo.setNowShopAddress(shop.getAddress());
                keyInfo.setShopGrade(shop.getGrade());
                Intent intent = new Intent(context, Store.class);
                intent.putExtra("keyInfo",keyInfo);
                context.startActivity(intent);
            }
        });
        holder.LBtnToBuy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                keyInfo.setNowFoodID(foods.get(position).getObjectId());
                keyInfo.setNowFoodName(foods.get(position).getName());
                final FoodSMInfo foodSMInfo = new FoodSMInfo(context, keyInfo);
                foodSMInfo.setSubmit(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Log.d(TAG, "在Food适配器获取食物数量：" + foodSMInfo.getFoodNumber());
                        String foodID = foods.get(position).getObjectId();
                        String userID = keyInfo.getUserID();
                        int foodAmount = foodSMInfo.getFoodNumber();
                        submitFoodTOCar(userID, foodID, foodAmount);
                        foodSMInfo.dismiss();
                        FoodToCar buyFoodAnimation = new FoodToCar(activity);
                        int[] to_location = getStartLocation(GET_END_LOCATION);
                        int[] from_location = getStartLocation(GET_START_LOCATION);
                        buyFoodAnimation.startAnim(from_location,to_location);
                    }
                });
                foodSMInfo.show();
            }
        });
    }

    @Override
    public int getItemCount() {
        return foods.size();
    }

    public void changeAdapter(List<Food> foods){
        this.foods.clear();
        this.foods=foods;
        notifyDataSetChanged();
    }

    /**
     * @param userID
     * @param foodID
     * @param foodAmount
     * @return
     *将食物提交到购物车
     */
    private void submitFoodTOCar(String userID, String foodID, final Integer foodAmount) {
        final Car car = new Car();
        Food food = new Food();
        food.setObjectId(foodID);
        car.setFood(food);
        car.setUserID(userID);
        car.setAmount(foodAmount);

        //查询用户是否添加过此食物，若添加过则添加数量，否则插入新数据
        BmobQuery<Car> query = new BmobQuery<Car>();
        query.addWhereEqualTo("food",new BmobPointer(food));
        BmobQuery<Car> query2 = new BmobQuery<Car>();
        query2.addWhereEqualTo("userID",userID);
        List<BmobQuery<Car>> qs = new ArrayList<BmobQuery<Car>>();
        qs.add(query);
        qs.add(query2);
        BmobQuery<Car> q = new BmobQuery<Car>();
        q.and(qs);
        q.findObjects(new FindListener<Car>() {
            @Override
            public void done(List<Car> list, BmobException e) {
                if (e == null){
                    if (list.size() == 0){
                        //购物车无记录，添加新数据
                        car.save(new SaveListener<String>() {
                            @Override
                            public void done(String s, BmobException e) {
                                if (e == null){
                                    Log.d(TAG, "添加数据到购物车 "+s);
                                } else {
                                    Toast.makeText(context, "服务器错误", Toast.LENGTH_SHORT).show();
                                    Log.d(TAG, "添加数据到购物车 "+e.getErrorCode()+e.getMessage());
                                }
                            }
                        });
                    } else{
                        //购物车有记录，更改数据
                        car.setObjectId(list.get(0).getObjectId());
                        car.setAmount(list.get(0).getAmount());
                        car.increment("amount",foodAmount);
                        car.update(new UpdateListener() {
                            @Override
                            public void done(BmobException e) {
                                if (e == null){
                                    Log.d(TAG, "更新购物车数据 ");
                                } else{
                                    Toast.makeText(context, "服务器错误", Toast.LENGTH_SHORT).show();
                                    Log.d(TAG, "更新购物车数据 "+e.getErrorCode()+e.getMessage());
                                }
                            }
                        });
                    }
                } else{
                    Toast.makeText(context, "服务器错误", Toast.LENGTH_SHORT).show();
                    Log.d(TAG, "查询用户是否添加过食物 :" +e.getErrorCode()+ e.getMessage());
                }
            }
        });

    }

    private int[] getStartLocation(int way){
        int[] location = new int[2];
        DisplayMetrics dm = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
        if (way == GET_START_LOCATION){
            location[0] = dm.widthPixels /2 ;
            location[1] = dm.heightPixels/2 + dm.heightPixels/15;
        } else if(way == GET_END_LOCATION){
            location[0] = 0;
            location[1] = dm.heightPixels/2 - dm.heightPixels/4;
        }
        return location;
    }

    public class SearchFoodViewHolder extends RecyclerView.ViewHolder{


        private TextView foodName;
        private ImageView foodImage;
        private TextView foodPrice;
        private LinearLayout LBtnToShop;
        private LinearLayout LBtnToBuy;

        public SearchFoodViewHolder(View itemView) {
            super(itemView);
            foodName = (TextView) itemView.findViewById(R.id.search_food_item_name);
            foodImage = (ImageView) itemView.findViewById(R.id.search_search_food_img);
            foodPrice = (TextView) itemView.findViewById(R.id.search_food_item_price);
            LBtnToShop = (LinearLayout) itemView.findViewById(R.id.search_food_item_goIn);
            LBtnToBuy = (LinearLayout) itemView.findViewById(R.id.search_food_item_buy);
        }
    }
}
